// pages/toolbar/passCheck/passCheck.js
import { comm } from '../../../behaviors/index'
import _ from '../../../utils/lodash/index'
import dayjs from '../../../utils/dayjs'
import WxValidate from '../../../utils/WxValidate'
import SpecialModel from '../../../api/special'
import { getStorage } from '../../../utils/storageSyncTool'
import Notify from '@vant/weapp/notify/notify'
import Toast from '@vant/weapp/toast/toast'
import Dialog from '@vant/weapp/dialog/dialog'
const computedBehavior = require('miniprogram-computed').behavior
const preachForm = {
  date: '',
  is_driver: false,
  vistor_name: '',
  vistor_phone: '',
  car_num: '',
  vistor_matter_id: 1,
  sex: 1,
}

Page({
  behaviors: [comm, computedBehavior],
  data: {
    ...preachForm, // 表单简易双向绑定数据
    isShare: false,
    uuid: '', //
    isComplate: false, // 是否创建完成
    // 弹窗选择
    showPickerSex: false, // 性别
    showPickerTime: false, // 日期
    showPickerType: false, //来访是由
    sexTypes: [
      { id: 1, text: '男' },
      { id: 2, text: '女' },
      // { id: 3, text: '未知' },
    ],
    typesColumns: [],
    // 时间选择
    minDate: new Date().getTime(),
    currentDate: '',
    completeInfo: {
      访客姓名: {
        mapping: 'vistor_name',
        value: '/',
      },
      访客手机号: {
        mapping: 'vistor_phone',
        value: '/',
      },
      来访事由: {
        mapping: 'typeTxt',
        value: '/',
      },
      访客性别: {
        mapping: 'sexTxt',
        value: '/',
      },
      到访时间: {
        mapping: 'date',
        value: '/',
      },
      是否驾车: {
        mapping: 'isDriveTxt',
        value: '/',
      },
      车牌号码: {
        mapping: 'car_num',
        value: '/',
      },
    },

    // 录入人脸
    fileList: [],
  },
  computed: {
    // 选中性别文本
    sexTxt({ sex, sexTypes }) {
      return (sexTypes.find((v) => v.id === sex) || {}).text
    },
    // 是否驾车文本
    isDriveTxt({ is_driver }) {
      return is_driver ? '是' : '否'
    },
    typeTxt({ vistor_matter_id, typesColumns }) {
      return (typesColumns.find((v) => v.id === vistor_matter_id) || {}).text
    },
  },
  watch: {
    // 选中日期时间戳格式化为 日期字符串
    currentDate(time) {
      if (!time) return false
      let date = dayjs(time).format('YYYY-MM-DD')
      this.setData({
        date,
      })
    },
  },
  onLoad: function ({ uuid }) {
    let isShare = Boolean(uuid)
    this.setData({ isShare, uuid })
    let status = getStorage('status')
    this.setData({
      userStatus: status,
    })
    SpecialModel.passType()
      .then(({ data }) => {
        data.forEach(function (item) {
          item.text = item.name
          item.defaultIndex = item.id
        })
        this.setData({
          typesColumns: data,
        })
      })
      .catch((err) => {})
    // this.initValidate()

    if (isShare) {
      this.initPassCheckCard(uuid)
    }
  },
  // 页面转发
  onShareAppMessage: function ({ from }) {
    let _that = this
    let userStatus = _that.data.userStatus
    if (userStatus == 1) {
      return Toast('等待管理员完成实名审核')
    } else if (userStatus == 0 || userStatus == 3) {
      return Dialog.confirm({
        title: '提示',
        message: '请先完善实名信息',
        confirmButtonText: '页面跳转',
      })
        .then(() => {
          wx.navigateTo({
            url: '/subPackages/otherPackages/pages/realnameregistration/index',
          })
        })
        .catch(() => {})
    }
    let { uuid } = this.data
    switch (from) {
      case 'button': // 页内按钮转发
        return {
          title: '通行证',
          path: `/pages/toolbar/passCheck/passCheck?uuid=${uuid}`,
        }

      default:
        // 右上角菜单“转发”
        return {}
    }
  },
  // 提交通行证
  submitPassCheckForm() {
    let _that = this
    let userStatus = _that.data.userStatus
    if (userStatus == 1) {
      return Toast('等待管理员完成实名审核')
    } else if (userStatus == 0 || userStatus == 3) {
      return Dialog.confirm({
        title: '提示',
        message: '请先完善实名信息',
        confirmButtonText: '页面跳转',
      })
        .then(() => {
          wx.navigateTo({
            url: '/subPackages/otherPackages/pages/realnameregistration/index',
          })
        })
        .catch(() => {})
    }
    this.initValidate()
    let params = _.pick(this.data, Object.keys(preachForm))
    if (!this.WxValidate.checkForm(params)) {
      const { msg: message } = this.WxValidate.errorList[0]
      Notify({ type: 'warning', message })
    } else {
      // 验证通过 》
      wx.showLoading({ title: '创建中...', mask: true })
      params.is_driver = params.is_driver ? '1' : '0'
      SpecialModel.setPassCheck(params)
        // new Promise(resolve => setTimeout(() => resolve({ data: demo }), 3000))
        .then(({ data }) => {
          wx.hideLoading()
          let { completeInfo } = this.data
          this.setData(
            {
              ...data,
            },
            () => {
              for (const [key, val] of Object.entries(completeInfo)) {
                completeInfo[key].value = this.data[val.mapping]
              }
              this.setData({ completeInfo, isComplate: true })
            }
          )
        })
        .catch((err) => {})
      // .finally(() => wx.hideLoading())
    }
  },
  // 上传人脸图
  submitFaceMap({ detail }) {
    wx.showLoading({ title: '上传中...', mask: true })
    let { file } = detail
    new Promise((success, fail) =>
      wx.getFileSystemManager().readFile({
        success,
        fail,
        encoding: 'base64',
        filePath: file.url,
      })
    )
      .then(({ data }) => {
        let name = file.url.split('/').pop()
        // return new Promise((resolve) => setTimeout(() => resolve(), 2000))
        return SpecialModel.setVisitorImg(this.data.id, {
          face_img: { name, data },
        })
      })
      .then(() => {
        Toast.success('人脸录入成功')
      })
      .catch((err) => {})
      .finally(() => wx.hideLoading())
  },
  // 获取行程卡
  initPassCheckCard(uuid) {
    wx.showLoading({ title: '绑定中...', mask: true })
    SpecialModel.setBindPassCheck(uuid)
      // new Promise(resolve => setTimeout(() => resolve({ data: demo }), 2000))
      .then(({ data }) => {
        Toast.success('绑定成功！')
        let { completeInfo } = this.data
        this.setData(
          {
            ...data,
          },
          () => {
            for (const [key, val] of Object.entries(completeInfo)) {
              completeInfo[key].value = this.data[val.mapping]
            }
            this.setData({ completeInfo })
          }
        )
      })
      .catch(({ errCode, data }) => {
        if (errCode === 10060) {
          let errMsg = Object.values(data)[0][0]
          Dialog.alert({
            title: '提示',
            message: `${errMsg}，确认后回退到首页`,
          }).then(() => {
            wx.redirectTo({ url: `/pages/index/index` })
          })
        }
      })
      .finally(() => wx.hideLoading())
  },
  // 表单校验规则
  initValidate() {
    let rules = {},
      message = {}
    if (this.data.is_drive) {
      ;(rules = {
        vistor_name: {
          required: true,
        },
        vistor_phone: {
          required: true,
        },
        date: {
          required: true,
        },
        car_num: {
          required: true,
        },
      }),
        (message = {
          vistor_name: {
            required: '访客姓名不能为空！',
          },
          vistor_phone: {
            required: '请填写访客手机号！',
          },
          date: {
            required: '请选择到访时间',
          },
          car_num: {
            required: '请填写车辆牌照',
          },
        })
    } else {
      ;(rules = {
        vistor_name: {
          required: true,
        },
        vistor_phone: {
          required: true,
        },
        date: {
          required: true,
        },
      }),
        (message = {
          vistor_name: {
            required: '访客姓名不能为空！',
          },
          vistor_phone: {
            required: '请填写访客手机号！',
          },
          date: {
            required: '请选择到访时间',
          },
        })
    }
    this.WxValidate = new WxValidate(rules, message)
  },
  restForm() {
    this.preachForm = Object.assign({}, preachForm)
    this.fileList = []
  },
  openPickerSex() {
    this.setData({
      showPickerSex: true,
    })
  },
  openPickerType() {
    this.setData({
      showPickerType: true,
    })
  },
  onCancel() {
    this.setData({
      showPickerType: false,
    })
  },
  closePickerSex() {
    this.setData({
      showPickerSex: false,
    })
  },
  openPickerTime() {
    this.setData({
      showPickerTime: true,
    })
  },
  closePickerTime() {
    this.setData({
      showPickerTime: false,
    })
  },
  // 选中性别
  changeSex(event) {
    const { value } = event.detail
    this.setData({ sex: value.id, showPickerSex: false })
  },
  // 选中来访是由
  onConfirm(event) {
    const { value } = event.detail
    this.setData({ vistor_matter_id: value.id, showPickerType: false })
  },
  // 切换是否驾车
  toggleStatus({ detail }) {
    this.setData({
      is_driver: detail,
    })
  },
  // 选中日期
  changeVisitTime({ detail }) {
    this.setData({
      currentDate: detail,
      showPickerTime: false,
    })
  },

  checkList() {
    let _that = this
    let userStatus = _that.data.userStatus
    if (userStatus == 1) {
      return Toast('等待管理员完成实名审核')
    } else if (userStatus == 0 || userStatus == 3) {
      return Dialog.confirm({
        title: '提示',
        message: '请先完善实名信息',
        confirmButtonText: '页面跳转',
      })
        .then(() => {
          wx.navigateTo({
            url: '/subPackages/otherPackages/pages/realnameregistration/index',
          })
        })
        .catch(() => {})
    }
    wx.navigateTo({
      url: `/pages/toolbar/passList/index`,
    })
  },

  // 预览二维码
  previewQRcode(e) {
    let { url } = e.currentTarget.dataset
    wx.previewImage({ urls: [url] })
  },
})
